/*
 * @Description:
 * @Autor: fage
 * @Date: 2022-07-07 14:36:09
 * @LastEditors: chenbinfa
 * @LastEditTime: 2022-08-18 17:39:21
 */
import styled from "styled-components";
import React, { useRef, useState, useEffect } from "react";
import { DatePicker, Input, Menu, Modal, Button, Dropdown, Descriptions, Select, Space, Table, message, Tabs, Popconfirm, Checkbox, Card, Form } from "antd";
import { DeleteOutlined, EditOutlined, VideoCameraOutlined, AudioOutlined, AndroidOutlined } from "@ant-design/icons";
import _ from "lodash";
import { formatterCurrency, formatBalanceStr, formatterSize, formatterSizeFromMB } from "@utils/formatter";
import { ThTable } from "@/components/ThTable";
import { operation, NewFileMetadata, updateFileMetadata, deleteFileMetadata } from "../../services/graphql";
import * as antdHelper from "../../utils/antd-helper";
import { getFileType } from "../../utils/file-helper";
import store from "../../utils/store";

const Main = ({ className }) => {
	let ChildRef = React.createRef();
	const [tab, setTab] = useState(0);
	const [fileType, setFileType] = useState("video");
	const [showEditBox, setShowEditBox] = useState(false);
	const [loading, setLoading] = useState(false);
	const [data, setData] = useState({});
	const [editItem, setEditItem] = useState({});
	const [timems, setTimems] = useState(0);
	const loadData = async params => {
		setLoading(true);
		let ret = await operation(params);
		console.log(ret);
		setLoading(false);
		return ret;
	};
	const onEdit = item => {
		setEditItem(item);
		setShowEditBox(true);
	};
	const onDelete = async id => {
		antdHelper.loading("loading");
		let ret = await deleteFileMetadata(id);
		if (ret.msg == "ok") {
			antdHelper.notiOK("Delete success");
			setTimems(new Date().valueOf());
		}
		antdHelper.loading();
	};
	const onSave = async values => {
		console.log({ values });
		if (isNaN(values.sort)) {
			return antdHelper.alertError("Sort must a number.");
		}
		if (values.displayFid.length < 40) {
			return antdHelper.alertError("displayFid error.");
		}
		if (values.fid.length < 40) {
			return antdHelper.alertError("Fid error.");
		}
		if (values.title.length < 3) {
			return antdHelper.alertError("Name less than 3 char.");
		}
		setLoading(true);
		let ret;
		values.fileType = fileType;
		values.sort = parseInt(values.sort);
		values.latestEditor = store.get("identity");
		if (editItem.id) {
			values.id = editItem.id;
			ret = await updateFileMetadata(values);
		} else {
			ret = await NewFileMetadata(values);
		}
		if (ret && ret.msg == "ok") {
			antdHelper.notiOK("Save success");
			setTimems(new Date().valueOf());
			setShowEditBox(false);
		}
		setLoading(false);
	};

	const prop1 = {
		border: true,
		size: "middle",
		pagesize: 20,
		titleBar: {
			title: "Video",
			btns: [
				{
					label: "Add item",
					type: "add",
					key: "1",
					func: function () {
						setEditItem({});
						setShowEditBox(true);
					}
				}
			]
		},
		loadList: {
			params: {
				filter: "video"
			},
			method: loadData
		},
		table: {
			columns: [
				{
					title: "Sort",
					dataIndex: "sort",
					key: "sort",
					width: 50
				},
				{
					title: "Creation time",
					dataIndex: "creationTime",
					key: "creationTime",
					width: "15%",
					textWrap: "word-break",
					ellipsis: true
				},
				{
					title: "Name",
					dataIndex: "title",
					key: "title",
					width: "15%",
					textWrap: "word-break",
					ellipsis: true
				},
				{
					title: "Fid",
					dataIndex: "fid",
					key: "fid",
					width: "15%",
					textWrap: "word-break",
					ellipsis: true
				},
				{
					title: "Display picture fid",
					dataIndex: "displayFid",
					key: "displayFid",
					width: "15%",
					textWrap: "word-break",
					ellipsis: true
				},
				{
					title: "Latest Editor",
					dataIndex: "latestEditor",
					key: "latestEditor",
					width: "15%",
					textWrap: "word-break",
					ellipsis: true
				},
				{
					title: "Operation",
					key: "operation",
					fixed: "right",
					width: 120,
					render: (text, record) => (
						<Space>
							<Button type="link" icon={<EditOutlined />} onClick={e => onEdit(record)}>
								Edit
							</Button>
							<Popconfirm title="Delete the item" description="Are you sure to delete this item?" onConfirm={e => onDelete(record.id)} okText="Yes" cancelText="No">
								<Button danger icon={<DeleteOutlined />} type="link">
									Delete
								</Button>
							</Popconfirm>
						</Space>
					)
				}
			]
		}
	};
	const prop2 = _.cloneDeep(prop1);
	prop2.titleBar.title = "Music";
	prop2.loadList.params.filter = "music";
	const prop3 = _.cloneDeep(prop1);
	prop3.titleBar.title = "Application";
	prop3.loadList.params.filter = "application";

	let tabItems = [
		<span>
			<VideoCameraOutlined />
			Video
		</span>,
		<span>
			<AudioOutlined />
			Music
		</span>,
		<span>
			<AndroidOutlined />
			Application
		</span>
	];
	const onTabChange = i => {
		setTab(i);
		let type = i == 0 ? "video" : i == 1 ? "music" : "application";
		setFileType(type);
	};

	return (
		<div className={className}>
			<Tabs
				defaultActiveKey="0"
				onChange={i => onTabChange(i)}
				style={{ padding: 10 }}
				items={tabItems.map((item, i) => {
					return {
						label: item,
						key: i + "",
						children: ""
					};
				})}
			/>
			<div className={"box box-0-" + tab}>
				<ThTable props={prop1} onRef={ChildRef} timems={timems} />
			</div>
			<div className={"box box-1-" + tab}>
				<ThTable props={prop2} onRef={ChildRef} timems={timems} />
			</div>
			<div className={"box box-2-" + tab}>
				<ThTable props={prop3} onRef={ChildRef} timems={timems} />
			</div>

			{showEditBox ? (
				<Modal footer={false} title={editItem.id ? "Update item" : "Add item"} width="60%" open={true} onCancel={() => setShowEditBox(false)}>
					<Form
						name="basic"
						labelCol={{
							span: 8
						}}
						wrapperCol={{
							span: 16
						}}
						style={{
							maxWidth: 600
						}}
						initialValues={editItem}
						onFinish={onSave}
						autoComplete="off">
						<Form.Item
							label="Sort"
							name="sort"
							rules={[
								{
									required: true,
									message: "Please input a number!"
								}
							]}>
							<Input type="number" />
						</Form.Item>
						<Form.Item
							label="Name"
							name="title"
							rules={[
								{
									required: true,
									message: "Please input a name!"
								}
							]}>
							<Input />
						</Form.Item>
						<Form.Item
							label="Fid"
							name="fid"
							rules={[
								{
									required: true,
									message: "Please input a fid!"
								}
							]}>
							<Input />
						</Form.Item>
						<Form.Item
							label="Display picture fid"
							name="displayFid"
							rules={[
								{
									required: true,
									message: "Please input a displayFid!"
								}
							]}>
							<Input placeholder="width:282px,height:440px" />
						</Form.Item>

						<Form.Item
							wrapperCol={{
								offset: 8,
								span: 16
							}}>
							<Button loading={loading} disabled={loading} type="primary" htmlType="submit">
								Submit
							</Button>
						</Form.Item>
					</Form>
				</Modal>
			) : (
				""
			)}
		</div>
	);
};

export default styled(Main)`
	.box {
		display: none;
	}
	.box-0-0,
	.box-1-1,
	.box-2-2 {
		display: block !important;
	}
`;
